package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.widget.LoadingView;

import logic.bean.BookInfo;
import logic.bean.TrainExamCoursewareDetailBean;
import logic.constants.DefaultConsts;
import logic.util.Util;
import logic.util.logutil.LogUtil;

/**
 * 移动培训详情界面
 */
public class TrainExamCommonWebActivity extends BaseBusinessActivity implements OnClickListener {

    private WebView webView = null;
    private WebChromeClient chromeClient = null;
    private View myView = null; //全频时View显示
    private Button btnBack = null;
    private FrameLayout fLayWebView = null;
    private View rlayTitle = null;
    private CustomViewCallback myCallBack = null;
    private LoadingView loadingView = null;

    private String mTitle = "";
    private String mUrl = "";
    private String targetType = "";
    /**
     * 是否为考试
     */
    private boolean isExam = false;
    private boolean isThrough = false;

    @Override
    public Handler getUIHandler() {
        return myHandler;
    }

    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            switch (msg.what) {
                case 1:
                    String bookId = bundle.getString("bookId");
                    String name = bundle.getString("bookName");
                    String type = bundle.getString("bookType");
                    gotoBookDetail(bookId, name, type);
                    break;
                case 2:
                    TrainExamCoursewareDetailBean bean = (TrainExamCoursewareDetailBean) bundle.getSerializable("detail");
                    gotoWareDetail(bean);
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.webview_lay);
        final Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey(DefaultConsts.title_s)) {
                mTitle = bundle.getString(DefaultConsts.title_s);
            }
            mUrl = bundle.getString(DefaultConsts.req_url_s);
            if (mUrl != null) {
                if (mUrl.contains("toTrainExamQuestion.do") || mUrl.contains("toEvaluatingView.do")) {
                    //正在考试按返回弹框
                    isExam = true;
                }
            }
        }

        initView();
        initLoadingView();
        setListener();
        setWebView();

        if (savedInstanceState != null) {
            webView.restoreState(savedInstanceState);
        }
    }

    void initView() {
        fLayWebView = (FrameLayout) findViewById(R.id.webview_flay);
        webView = (WebView) findViewById(R.id.webview_web);
        TextView tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText(mTitle);
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        rlayTitle = findViewById(R.id.common_title_layout);
        loadingView = (LoadingView) findViewById(R.id.webview_loading_view);
    }

    private void initLoadingView() {
        loadingView.setLoadingAnim(R.drawable.home_progress);
        //		loadingView.setLoadingAnim(R.anim.column_switch_anim);
        loadingView.changeLoadingStatus(0);

        loadingView.setVisibility(View.VISIBLE);
        /* 用GONE会导致部分视频加载不出来 */
        fLayWebView.setVisibility(View.INVISIBLE);
    }

    void setListener() {
        btnBack.setOnClickListener(this);
    }

    @SuppressLint("SetJavaScriptEnabled")
    void setWebView() {
        WebSettings webSetting = webView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);

        webView.setWebViewClient(new MyWebViewClient());

        chromeClient = new MyChromeClient();

        webView.setWebChromeClient(chromeClient);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(true);

        webSetting.setSupportZoom(false);
        webSetting.setPluginState(WebSettings.PluginState.ON);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setUseWideViewPort(true); //适应屏幕

        if (Util.isEmpty(mUrl)) {
            loadingView.setVisibility(View.GONE);
            fLayWebView.setVisibility(View.VISIBLE);
        } else {
            webView.loadUrl(mUrl);
        }
        webView.addJavascriptInterface(new SubMaintenanceJavaScriptInterface(), "qyreader");
    }

    @Override
    public void onBackPressed() {
        if (myView != null) {
            chromeClient.onHideCustomView();//退出全屏
            return;
        }
        if (isExam) {//考试页面
            sureAction();
            return;
        }
        if (webView.canGoBack() && !"5".equals(targetType)) {
            webView.goBack();
        } else {
            webView.onPause(); //停止
            if (!existMainActivity()) {//当MainActivity没有启动则跳转到MainActivity
                startActivity(new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
            }
            setResult(RESULT_OK);
            super.onBackPressed();
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        webView.saveState(outState);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return super.shouldInterceptRequest(view, request);
        }

        /*
         * 点击页面的某条链接进行跳转的话，会启动系统的默认浏览器进行加载，调出了我们本身的应用
         * 因此，要在shouldOverrideUrlLoading方法中
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //使用当前的WebView加载页面
            if (url.contains("toTrainExamQuestion.do") || url.contains("toEvaluatingView.do")) {
                isExam = true;
            }
            if (url.contains("tel:")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_DIAL);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }
            view.loadUrl(url);
            return true;
        }

        /*
         * 网页开始加载
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        /*
         * 网页加载完毕(仅指主页，不包括图片)
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (url.contains("queryChapterInfoView.do")) {
                //学习记录子评测
                queryChapterInfo();
            }
            loadingView.setVisibility(View.GONE);
            fLayWebView.setVisibility(View.VISIBLE);
        }

        /*
         * 加载页面资源
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        /*
         * 错误提示
         */
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            LogUtil.e("webView", description);
            super.onReceivedError(view, errorCode, description, failingUrl);
            loadingView.setVisibility(View.GONE);
            fLayWebView.setVisibility(View.VISIBLE);
        }

    }

    @JavascriptInterface
    public void sureAction() {
        myHandler.post(new Runnable() {
            @Override
            public void run() {
                //调用js中的onJsAndroid方法
                webView.loadUrl("javascript:sureAction()");
            }
        });
    }

    @JavascriptInterface
    public void queryChapterInfo() {
        myHandler.post(new Runnable() {
            @Override
            public void run() {
                //调用js中的onJsAndroid方法
                isThrough = true;
                webView.loadUrl("javascript:qryTrainChapterInfo()");
            }
        });
    }

    private class MyChromeClient extends WebChromeClient {

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (myView != null) {
                callback.onCustomViewHidden();
                return;
            }
            fLayWebView.removeView(webView);
            fLayWebView.addView(view);
            rlayTitle.setVisibility(View.GONE);
            myView = view;
            myCallBack = callback;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        }

        @Override
        public void onHideCustomView() {
            if (myView == null) {
                return;
            }
            fLayWebView.removeView(myView);
            myView = null;
            fLayWebView.addView(webView);

            rlayTitle.setVisibility(View.VISIBLE);
            myCallBack.onCustomViewHidden();
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.d("ZR", consoleMessage.message() + " at " + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber());
            return super.onConsoleMessage(consoleMessage);
        }

        /*
         * 此处覆盖的是javascript中的alert方法。
         * 当网页需要弹出alert窗口时，会执行onJsAlert中的方法
         * 网页自身的alert方法不会被调用。
         */
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            /*
             * 此处代码非常重要，若没有，android就不能与js继续进行交互了，
			 * 且第一次交互后，webview不再展示出来。
			 * result：A JsResult to confirm that the user hit enter.
			 * 我的理解是，confirm代表着此次交互执行完毕。只有执行完毕了，才可以进行下一次交互。
			 */
            result.confirm();
            return true;
        }

        /*
         * 此处覆盖的是javascript中的confirm方法。
         * 当网页需要弹出confirm窗口时，会执行onJsConfirm中的方法
         * 网页自身的confirm方法不会被调用。
         */
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return true;
        }

        /*
         * 此处覆盖的是javascript中的confirm方法。
         * 当网页需要弹出confirm窗口时，会执行onJsConfirm中的方法
         * 网页自身的confirm方法不会被调用。
         */
        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            return true;
        }

        /*
         * 如果页面被强制关闭,弹窗提示：是否确定离开？
         * 点击确定 保存数据离开，点击取消，停留在当前页面
         */
        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            return true;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    private void sendToastMessage(String bookId, String bookName, String bookType) {
        Message msg = Message.obtain();
        msg.what = 1;
        Bundle bundle = new Bundle();
        bundle.putString("bookId", bookId);
        bundle.putString("bookName", bookName);
        bundle.putString("bookType", bookType);
        msg.setData(bundle);
        myHandler.sendMessage(msg);
    }

    private void preGotoWareDetail(TrainExamCoursewareDetailBean bean) {
        Message msg = Message.obtain();
        msg.what = 2;
        Bundle bundle = new Bundle();
        bundle.putSerializable("detail", bean);
        msg.setData(bundle);
        myHandler.sendMessage(msg);
    }

    /**
     * 跳转到书籍详情
     *
     * @param bookId   书籍id
     * @param name     书籍名称
     * @param bookType 书籍类型
     */
    private void gotoBookDetail(String bookId, String name, String bookType) {
        if (isThrough) {
            finish();
        }
        BookInfo info = new BookInfo();
        info.setBookId(Long.parseLong(bookId));
        info.setName(name);
        info.setContent_type(bookType);
        Intent intent = new Intent(this, NewBookDetailActivity.class);
        intent.putExtra("BookInfo", info);
        startActivity(intent);
    }

    /**
     * 跳转到文档阅读界面
     */
    private void gotoWareDetail(TrainExamCoursewareDetailBean bean) {
        if (isThrough) {
            finish();
        }
        Intent detailIntent = new Intent(this, CoursewareReadActivity.class);
        detailIntent.putExtra("detail", bean);
        startActivity(detailIntent);
    }

    final class SubMaintenanceJavaScriptInterface {
        /**
         * 在屏幕下端提示用户
         */
        @JavascriptInterface
        public void setBookInfo(String bookId, String bookName, String bookType) {
            LogUtil.d("--", "bookId：" + bookId + " | bookName:" + bookName + " |bookType:" + bookType);
            sendToastMessage(bookId, bookName, bookType);
        }

        /**
         * 提供给B端打印日志
         */
        @JavascriptInterface
        public void fireLog(String log) {
            LogUtil.d("log", log);
        }

        /**
         * 假如有历史记录 回退历史记录 否则退出容器
         */
        @JavascriptInterface
        public void goBack() {
//			BaseBusinessActivity.uiHandler.post(new Runnable()
//			{
//				@Override
//				public void run() {
            isExam = false;
//					onBackPressed();
            TrainExamCommonWebActivity.this.finish();
//				}
//			});
        }

        @JavascriptInterface
        public void setCourseInfo(String url, String page, String size, String chapterId, String name, String shortIntro, String lecturerName, String typeName, String hasExam, String evaluateType, String school) {
            TrainExamCoursewareDetailBean bean = new TrainExamCoursewareDetailBean();
            bean.setUrl(url);
            bean.setPage(Integer.parseInt(page));
            bean.setSize(Integer.parseInt(size));
            bean.setChapterId(Integer.parseInt(chapterId));
            bean.setName(name);
            bean.setShortIntro(shortIntro);
            bean.setLecturerName(lecturerName);
            bean.setHasExam(hasExam);
            bean.setEvalueteType(Integer.parseInt(evaluateType));
            bean.setTypeName(typeName);
            bean.setSchool(school);
            preGotoWareDetail(bean);
        }
    }
}
